package pl.szpadel.android.gadu.packets;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.WritableByteChannel;

/// Base class for packets that can be serialised and send
public abstract class SendPacket extends BasePacket {

	/// Reimplementable - writes packet content to buffer
	protected abstract void writeToBuffer(ByteBuffer buffer) throws BufferOverflowException;
	
	/// Common buffer used to build packets
	private static ByteBuffer mBuffer = ByteBuffer.allocateDirect(4096);
	
	
	@SuppressWarnings("unused")
	private final static String TAG = "SendPacket";
	
	/// C-tor
	public SendPacket(int type) {
		super(type);
	}
		
	/// Sends packet to channel
	public void toChannel(WritableByteChannel channel) throws IOException {
		mBuffer.clear();
		mBuffer.order(ByteOrder.LITTLE_ENDIAN);

		try {
			writeToBuffer(mBuffer);
		} catch ( BufferOverflowException e ) {
			throw new IOException("Insanely big packet");
		}
	
		// now create header
		mBuffer.flip();
		
		Header header = new Header(getType(), mBuffer.limit());
		header.toChannel(channel);
		
		channel.write(mBuffer);
	}
			
	/// Tool puting string into buffer using gg convention (int with len, then content w/o terminator)
	static protected void putString(ByteBuffer buf, String str) {
		buf.putInt(str.length());
		if (str.length() > 0){
			try {
				buf.put(str.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				; // ignore
			}
		}
	}
	
}
